# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import datetime,logging
from .sqlitedb import (db2dict,majdb3,ralldb3,reqdb3)


logger = logging.getLogger()


def labelofdev(type,subtype):
    req = "SELECT label FROM labeldevice WHERE type = ? AND stype = ?;"
    r = reqdb3(req,[type,subtype])
    if r:
        label = r[0].replace(' ','_')
        return label[:20]
    return None


def newalias(item):
    """
    item = [typeunit,unit,alias]
    typeunit = ['detector','device','sensor']
    unit = addrid or hu
    alias = name / label of the unit
    """
    req = "SELECT rowId FROM alias WHERE typeunit = ? and unit = ?;"
    r = reqdb3(req,item[0:2])
    if r:	#replace for unit existant
        req = 'UPDATE alias SET label = ? WHERE rowId = ?;'
        majdb3(req,[item[2],r[0],])
        return 'Update Alias %s for Unit %s' % (item[2],item[1])
    else:
        req = "INSERT INTO alias(typeunit,unit,label) VALUES (?,?,?);"
        majdb3(req,item)
        return 'Add New Alias %s for Unit %s' % (item[2],item[1])


def newchu(listhc):
    hu = None
    for hc in listhc:
        for uc in range(1,17):
            hu = hc + str(uc)
            req = "SELECT unit FROM alias WHERE unit = ?;"
            row = reqdb3(req,[hu,])
            if row is None:
                break
        if hu:
            break
    return hu


def newhu(typeunit):
    """
    Generate a new houseunit according to typeunit
    after checking non existence in alias
    """
    if typeunit == 'sensor':
        hu = newchu(['L','M','N','O'])
    elif typeunit == 'detector':
        hu = newchu(['I','J','K'])
    elif typeunit == 'device':
        hu = newchu(['B','C','D','E','F','G'])
    else:
        hu = None
    if hu:
        req = "INSERT INTO alias(typeunit,label,unit) VALUES (?,?,?);"
        majdb3(req,[typeunit,hu,hu])
    return hu


def newid(item):
    """
    item = [typeunit,unitid]
    item = [typeunit,unitid,type,subtype]
    typeunit = ['detector','device','remote','sensor']
    unitid = addrid (hex form) or hu (houseunit)
    """
    hu = None
    if item[1].startswith('0x'):
        hu = newhu(item[1])
    if hu is None: hu = item[1]
    name = item[0] + '_' + hu
    label = None
    if len(item) == 4:
        label =  labelofdev(item[2],item[3])
    if label is None: label = name
    return [item[1],hu, name, label]


def sensorid(item):
    """
    item =  [protocol,model,typeunit,model_addr,type,subtype,listdata]
    """
    unitid,unit,name,label = newid(item[2:6])
    d = datetime.date.strftime(datetime.datetime.today(),"%Y-%m-%d %H:%M:%S").split()
    listdata = item[6].split()
    try:
        req = "INSERT INTO unitIds(cdate,ctime,iddecoder,modelId,unitId,unit,label,typeunit,enabled) "
        req += " VALUES (?,?,?,?,?,?,?,?,?);"
        majdb3(req,[d[0], d[1], item[0], item[1], unitid, unit, label,'sensor','True'])
        newalias(['sensor', unit, name])
        for parameter in listdata:
            req = "INSERT INTO parameterIds(modaddrId,parameter) VALUES (?,?);"
            majdb3(req,[unitid,parameter])
    except Exception as e:
        logger.error("Update failed for newids with error : %s",repr(e))
    return db2dict("UNITIDS"," WHERE typeunit = 'sensor'")


def unitid(item):
    """
    typeunit = ['device','detector','remote']
    item = [protocol,model,typeunit,addrid]
    item = [protocol,model,typeunit,addrid,type,subtype]
    """
    d = datetime.date.strftime(datetime.datetime.today(),"%Y-%m-%d %H:%M:%S").split()
    typeunit = item[2]
    addrid,hu,name,label = newid(item[2:])
    try:
        req = "INSERT INTO unitIds(cdate,ctime,iddecoder,modelId,unitId,unit,label,typeunit) VALUES (?,?,?,?,?,?,?,?);"
        majdb3(req,[d[0], d[1], item[0], item[1], addrid, hu, label,typeunit])
        newalias([typeunit, hu, name])
    except Exception as e:
        logger.error("Update failed for newids with error : %s",repr(e))
    return db2dict("UNITIDS"," WHERE typeunit = '" + typeunit + "'")
